package net.wesley.android.city;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import net.wesley.android.City;

public class Hefei extends City {

	private String viewstate="";
	private String eventvalid="";

	public static byte[] convertInputStreamToByteArray(InputStream is) throws IOException
	{
		BufferedInputStream bis = new BufferedInputStream(is);
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		int result = bis.read();
		while(result !=-1)
		{
			byte b = (byte)result;
			buf.write(b);
			result = bis.read();
		}
		return buf.toByteArray();
	}
	
	public void requestParamsFinish(String[] values) {
		final String chejia4=values[0];
		final DefaultHttpClient httpClient = new DefaultHttpClient();  
		try {
			HttpGet get = new HttpGet("http://www.hfjjzd.gov.cn/hfwebquery/Default.aspx");
			HttpResponse rsp = httpClient.execute(get);
			BufferedReader br;
			br = new BufferedReader(new InputStreamReader(rsp.getEntity()
					.getContent(),"UTF-8"));
			String line, result = "";
			while ((line = br.readLine()) != null) result += line+"\n";
			int index=result.indexOf("id=\"__VIEWSTATE\" value=\"");
			if (index>0){
				viewstate=result.substring(index+24).split("\"")[0];
			}
			else{
				callback.onComplete(-10001, "");
				return;
			}
			
			index=result.indexOf("id=\"__EVENTVALIDATION\" value=\"");
			if (index>0){
				eventvalid=result.substring(index+30).split("\"")[0];
			}
			else{
				callback.onComplete(-10002, "");
				return;
			}
		
			HttpGet get2=new HttpGet("http://www.hfjjzd.gov.cn/hfwebquery/VerifyCode.aspx?");
			get2.setHeader("Referer", "http://www.hfjjzd.gov.cn/hfwebquery/Default.aspx");
			rsp = httpClient.execute(get2);	
			byte [] content = convertInputStreamToByteArray(rsp.getEntity().getContent());
			Bitmap bmp = BitmapFactory.decodeByteArray(content, 0, content.length);			
			if (bmp==null){
				callback.onComplete(-10006, "ret:获取验证码的时候遇到网络错误，请重试!");
				return;
			}
			LinearLayout table=new LinearLayout(ctx);
			table.setOrientation(LinearLayout.VERTICAL);
			ImageView v=new ImageView(ctx);
			v.setImageBitmap(bmp);
			v.setScaleType(ImageView.ScaleType.FIT_XY);
			LayoutParams p = new LinearLayout.LayoutParams(200,50);
			p.gravity=Gravity.CENTER;
			table.addView(v,p);
			final EditText t=new EditText(ctx);
			table.addView(t,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
			new AlertDialog.Builder(ctx).setTitle("请输入下图中的验证码").setView(table).setNegativeButton("确定", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					new Handler().postDelayed(new Runnable(){

						public void run() {
							HttpPost post=new HttpPost("http://www.hfjjzd.gov.cn/hfwebquery/Default.aspx");
							try {
								post.setEntity(new StringEntity(String.format("__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%s&__EVENTVALIDATION=%s&ctl00%%24ContentPlaceHolder1%%24ddrhpzl=02&ctl00%%24ContentPlaceHolder1%%24txthphm=%s&ctl00%%24ContentPlaceHolder1%%24butSearch=%%E6%%9F%%A5++%%E8%%AF%%A2&ctl00%%24ContentPlaceHolder1%%24txtclsbdh=%s&ctl00%%24ContentPlaceHolder1%%24txtcode=%s",
										URLEncoder.encode(viewstate), URLEncoder.encode(eventvalid),URLEncoder.encode(chepai,"UTF-8"),chejia4,t.getText().toString())));
								post.setHeader("Content-Type","application/x-www-form-urlencoded");
								post.setHeader("Referer", "http://www.hfjjzd.gov.cn/hfwebquery/Default.aspx");
								HttpResponse rsp = httpClient.execute(post);
								BufferedReader br;
								String line, result = "";
								br = new BufferedReader(new InputStreamReader(rsp.getEntity()
										.getContent(),"UTF-8"));
								while ((line = br.readLine()) != null) result += line+"\n";
								processResult(result);								
							} catch (UnsupportedEncodingException e) {
								callback.onComplete(-10003, "");
							} catch (ClientProtocolException e) {
								callback.onComplete(-10004, "");
							} catch (IOException e) {
								callback.onComplete(-10005, "");
							}
						}
					}, 1000);
				}
			}).create().show();
		} catch (ClientProtocolException e) {
			callback.onComplete(-10001, "");
		} catch (IOException e) {
			callback.onComplete(-10002, "");
		}
	}

	private void processResult(String result) {
		String tmp=result.split("<html ")[0];
		int index=tmp.indexOf(">alert('");
		if (index>0){
			callback.onComplete(-10031, "ret:"+tmp.substring(index+8).split("'")[0]);
			return;
		}
		int idx=result.indexOf("ctl00_ContentPlaceHolder1_GridView1");
		if (idx>0){
			String str=result.substring(idx).split("</div>")[0];
			String[] rows=str.split("<table");
			String retvalue="";
			for (int i=1;i<rows.length;i++){
				String[] cols=rows[i].split("<td");
				String shijian=cols[6].split("</td")[0].split(">")[1].replace("&nbsp;", "").trim();
				String didian=cols[10].split("</td")[0].split(">")[1].replace("&nbsp;", "").trim();
				String code=cols[12].split("</td")[0].split(">")[1].replace("&nbsp;", "").trim();
				retvalue+=String.format("shijian:%s\ndidian:%s\ncode:%s\n\n",shijian,didian,code);
			}
			callback.onComplete(rows.length-1, retvalue);
			return;
		}
		callback.onComplete(0, "");
	}	
	
	@Override
	public boolean match(String chepai) {
		return chepai.startsWith("皖A"); 
	}

	@Override
	public String[] paramDesc() {
		String[] s={"车辆识别代号后六位"};
		return s;
	}

}
